import json
import random
import re
from verifications import constants
from carts.utils import merge_cookie_redis_cart
from meiduo_mall.utils.response_code import RET
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render, redirect
from django import http
# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from celery_tasks.email_send.tasks import send_verify_url
from users.utils import MyLoginRequiredMiXinView, generate_verify_url, decode_verify_url
from .models import User, Address
from django.core.mail import send_mail
from goods.models import SKU
from itsdangerous import TimedJSONWebSignatureSerializer as TJSS

class RgisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 1.获取参数
        # 参数实际上是从表单中提交的html标签的value值，故需要根据前端html代码获取参数名称
        user_name = request.POST.get('user_name')
        password = request.POST.get('pwd')
        cpassword = request.POST.get('cpwd')
        phone = request.POST.get('phone')
        pic_code = request.POST.get('pic_code')
        msg_code = request.POST.get('msg_code')
        allow = request.POST.get('allow')

        # 2. 校验参数
        # 2.1 为空校验
        # print(user_name, password, cpassword, phone, pic_code, msg_code,allow)
        if not all([user_name, password, cpassword, phone, pic_code, msg_code,allow]):
            return http.HttpResponseForbidden('参数不全')

        # 2,2 两次密码校验
        if password != cpassword:
            return http.HttpResponseForbidden('两次密码不一致')

        # 2,3 手机号格式校验
        if not re.match(r'1[3-9]\d{9}', phone):
            return http.HttpResponseForbidden('手机号格式有误')

        # 2,4 短信验证码校验
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_code_%s' % phone).decode()
        if not redis_sms_code:
            return http.HttpResponseForbidden('验证码已过期')
        # print(redis_sms_code)
        if msg_code != redis_sms_code:
            return http.HttpResponseForbidden('验证码错误')

        # 2,5 协议校验
        if allow != 'on':
            return http.HttpResponseForbidden('必须同意协议')

        # 3. 创建用户对象，保存数据到数据库
        user = User.objects.create_user(username=user_name, password=password, mobile=phone)

        # 4. 返回响应
        response = redirect("/login")
        return response

class CheckUserNameView(View):
    # 校验的具体形式根据前端js代码确定
    # js中对输入格式校验成功后，会发送查重请求，要求返回json格式，并将data.count的值做为判断条件
    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        data = {
            "count":count
        }

        return http.JsonResponse(data)


class CheckMobileView(View):
    # 校验手机号重复
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            "count": count
        }

        return http.JsonResponse(data)

class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self,request):
        # 1，获取参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        # 2，校验参数
        # 为空校验
        if not all([username,password]):
            return http.HttpResponseForbidden('参数不全')

        # 用户名格式校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseForbidden("用户名格式有误")

        # 密码格式校验
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseForbidden("密码格式有误")
        # print(User.objects.get(username=username))
        # 3,密码和用户名正确性校验
        user = authenticate(request, username=username, password=password)

        if not user:
            return http.HttpResponseForbidden("账号或者密码错误")

        # 4,状态保持
        login(request,user) # 浏览器cookie默认保存登录信息,有效期两周
        if remembered == 'on':
            request.session.set_expiry(3600*24)
        else:
            request.session.set_expiry(0)
        # 5,返回响应
        response = redirect('/')
        response.set_cookie("username",user.username,3600*24*2)
        response = merge_cookie_redis_cart(user,request,response)
        return response

class LogoutView(View):
    def get(self, request):
        # 清除session
        logout(request)

        # 清除cookie
        response = redirect('/')
        response.delete_cookie("username")
        return response

# class UserCenterView(View):
#     def get(self, request):
#         # 方法一
#         # 判断是否已登录（有状态保持user）
#         # if request.user.is_authenticated:
#         #     return render(request,'user_center_info.html')
#         # else:
#         #     response = redirect('/login/')
#         #     # 防止session已删除，但浏览器中的cookie还存在
#         #     response.delete_cookie('username')
#         #     return response
#
#         # 方法二
#         return render(request, 'user_center_info.html')

# 方法三

class UserCenterView(MyLoginRequiredMiXinView):
    def get(self, request):
        # print('1--',request)
        # < WSGIRequest: GET '/info/' >
        data = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active,
            }
        return render(request, 'user_center_info.html', context=data)

class EmailSendView(MyLoginRequiredMiXinView):
    def put(self, request):
        # print(request)
        # < WSGIRequest: PUT '/emails/' >
        email_dict = json.loads(request.body.decode())
        email = email_dict.get('email')
        # print(email)

        # 判断参数
        if not email:
            return http.HttpResponseForbidden("参数缺失")

        # 格式校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden("邮箱格式有误")

        # 发送邮件
        verify_url = generate_verify_url(request.user)
        # print(verify_url)
        # 使用celery发送邮件
        send_verify_url.delay(verify_url,email)
        # send_mail(subject='邮箱激活',
        #           message='来了老弟',
        #           from_email=settings.EMAIL_FROM,
        #           recipient_list=[email])

        # 邮箱数据添加至数据库
        request.user.email = email
        request.user.save()

        # 返回响应
        return http.JsonResponse({"code": RET.OK, "errmsg": "ok"})

class EmailActiveView(View):
    def get(self,request):

        # 获取参数，校验参数
        token = request.GET.get('token')
        if not token:
            return  http.HttpResponseForbidden('token缺失')

        user = decode_verify_url(token)
        if not user:
            return http.HttpResponseForbidden('无效的token')

        # 数据入库
        user.email_active = True
        user.save()

        # 重定向
        return redirect('/info')

class AddressView(MyLoginRequiredMiXinView):
    def get(self,request):
        # 获取用户地址  related_name='addresses'
        addresses = request.user.addresses.filter(is_deleted=False)
        # 数据拼接
        addresses_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                # 前端 html--> :value="province.id" ; Js--> form_address.province_id
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id
            }
            addresses_list.append(address_dict)
        context = {
            "addresses": addresses_list,
            "default_address_id": request.user.default_address_id
            }
        return render(request,'user_center_site.html',context=context)

class AddressCreateView(MyLoginRequiredMiXinView):
    def post(self,request):
        # 1,获取参数(非表单类型 Non-Form Data）
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        # 2,校验参数
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.HttpResponseForbidden("参数不全")

        # 3,数据入库
        dict_data["user"] = request.user
        address = Address.objects.create(**dict_data)

        #4,返回响应 'response.data.address'
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email,
        }
        return http.JsonResponse({"code":RET.OK,"address":address_dict})

class AddressUpdateView(MyLoginRequiredMiXinView):
    # 修改地址
    def put(self, request, address_id):
        # 1,获取参数
        # '/addresses/' + this.addresses[this.editing_address_index].id + '/'
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        # 2,校验参数
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.HttpResponseForbidden("参数不全")

        #3,数据入库
        address = Address.objects.get(id=address_id)
        address.title = title
        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()

        # 4,返回响应  response.data.address
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email,
            # 前端 html--> :value="province.id" ; Js--> form_address.province_id
            # "province_id": address.province.id,
            # "city_id": address.city.id,
            # "district_id": address.district.id
        }
        return http.JsonResponse({"code": RET.OK, "address": address_dict})

    # 删除地址
    def delete(self, request, address_id):
        # 1,获取地址对象
        address = Address.objects.get(id=address_id)

        # 2,修改地址的is_deleted属性,入库
        address.is_deleted = True
        address.save()

        # 3,返回响应
        return http.JsonResponse({"code": RET.OK})

class AddressDefaultView(MyLoginRequiredMiXinView):
    def put(self,request, address_id):
        request.user.default_address_id = address_id
        request.user.save()

        return http.JsonResponse({"code": RET.OK})

class AddressTitleView(MyLoginRequiredMiXinView):
    def put(self,request,address_id):

        #1,获取参数
        title = json.loads(request.body.decode()).get("title")

        #2,为空校验参数
        if not title:
            return http.HttpResponseForbidden("参数不全")

        #3,数据入库
        ret = Address.objects.filter(id=address_id).update(title=title)
        if ret == 0:
            return http.HttpResponseForbidden("修改失败")

        #4,返回响应
        return http.JsonResponse({"code":RET.OK})

class PasswordChangeView(MyLoginRequiredMiXinView):
    def get(self,request):
        return render(request,'user_center_pass.html')

    def post(self,request):
        #1,获取参数
        old_pwd = request.POST.get("old_pwd")
        new_pwd = request.POST.get("new_pwd")
        new_cpwd = request.POST.get("new_cpwd")

        #2,校验参数
        #2.1为空校验
        if not all([old_pwd,new_pwd,new_cpwd]):
            return http.HttpResponseForbidden("参数不全")

        #2,2校验密码格式
        if not re.match(r'^[0-9A-Za-z]{8,20}$',old_pwd):
            return http.HttpResponseForbidden("旧密码格式有误")

        if not re.match(r'^[0-9A-Za-z]{8,20}$',new_pwd):
            return http.HttpResponseForbidden("旧密码格式有误")

        #2.3旧密码正确性
        if not request.user.check_password(old_pwd):
            return http.HttpResponseForbidden("旧密码不正确")

        #2.4两次新密码正确性
        if new_pwd != new_cpwd:
            return http.HttpResponseForbidden("两次新密码不一致")

        #3,数据入库
        request.user.set_password(new_pwd)
        request.user.save()

        #4,返回响应,清空session信息
        logout(request)
        response = redirect('/login')
        response.delete_cookie("username")
        return response

class UserBrowserHistoryView(MyLoginRequiredMiXinView):
    # detail.js 做post请求，保存浏览记录
    def post(self, request):
        # 1,获取参数
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")
        user = request.user

        # 2,校验参数
        if not sku_id:
            return http.HttpResponseForbidden("参数不全")
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden("商品不存在")

        # 3,数据入库(redis)
        redis_conn = get_redis_connection("histories")
        pipeline = redis_conn.pipeline()
        # 先去除重复数据，再将数据插至表头，切片截取数据
        pipeline.lrem("history_%s"%user.id, 0, sku_id)
        pipeline.lpush("history_%s"%user.id, sku_id)
        pipeline.ltrim("history_%s"%user.id, 0, 4)
        pipeline.execute()

        # 4,返回响应
        return http.JsonResponse({"code": RET.OK, "errmsg": "ok"})

    # user_center_info.js 做get请求，获取浏览记录
    def get(self, request):
        # 1,获取redis中的数据
        user = request.user
        redis_conn = get_redis_connection("histories")
        sku_ids = redis_conn.lrange("history_%s"%user.id,0,4)

        #2,拼接数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "id":sku.id,
                "default_image_url":sku.default_image_url.url,
                "name":sku.name,
                "price":sku.price,
            }
            sku_list.append(sku_dict)

        #3,返回
        return http.JsonResponse({"skus":sku_list})

class FindPwdView(View):
    def get(self,request):
        return render(request,"find_password.html")

class AccountsSmsView(View):
    def get(self,request,username):
        # 1,获取参数
        # user = request.COOKIES.get("user")
        # print(user)
        image_code = request.GET.get('text')
        image_code_id = request.GET.get('image_code_id')

        # 2，校验参数
        # 为空校验
        if not all([username, image_code, image_code_id]):
            return http.HttpResponseForbidden("参数不全")

        # 用户名格式校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden("用户名格式有误")

        # 图形验证码 正确性验证（从缓存中读取，判空，判误）
        redis_conn = get_redis_connection('code')
        redis_image_code = redis_conn.get('image_code_%s' % image_code_id)
        # print(redis_image_code,'&&')
        if not redis_image_code:
            return http.JsonResponse({"errmsg": "验证码已过期", "status": RET.DBERR})

        # 删除验证码，防止恶意匹配尝试
        redis_conn.delete('image_code_%s' % image_code_id)

        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({"errmsg": "图片验证码错误", "status": RET.DBERR})

        # 3,用户名正确性校验
        try:
            # 1,先判断username是否是手机号
            if re.match(r'^1[3-9]\d{9}$', username):

                user = User.objects.get(mobile=username)
            else:
                # 2,然后在通过用户名查询,用户
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return http.JsonResponse({"errmsg": "账号不存在", "status": RET.NODATA})
        # print(user,'**')

        # 4，查询手机号
        mobile = user.mobile
        # 3，拼接数据
        context = {
            "mobile":mobile,
            "mobile_show":mobile[:3]+'****'+mobile[7:],
        }
        # 4，返回响应
        return http.JsonResponse(context)

class SMScodeCheckView(View):
    def get(self,request):
        mobile = request.GET.get("mobile")
        # 发送短信验证码
        # 验证是否频繁获取验证码
        redis_conn = get_redis_connection('code')
        send_flag = redis_conn.get('sms_code_%s' % mobile)
        # if send_flag:
        #     return http.JsonResponse({"errmsg": "操作过于频繁，请稍候重试", "code": RET.SMSCODERR})

        # 生成验证码并发送
        sms_code = '%06d' % random.randint(0, 999999)

        # 使用celery发送短信
        from celery_tasks.sms_send.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, constants.REDIS_SMS_CODE_EXPIRES / 60)
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, constants.REDIS_SMS_CODE_EXPIRES / 60], 1)

        # 将验证码存入redis缓存
        # 使用pipeline管道
        pipe = redis_conn.pipeline()
        pipe.setex('sms_code_%s' % mobile, constants.REDIS_SMS_CODE_EXPIRES, sms_code)
        pipe.setex('send_flag_%s' % mobile, constants.REDIS_SEND_FLAG_EXPIRES, 1)
        pipe.execute()

        print(redis_conn.get('sms_code_%s' % mobile))

        # # 生成access_token
        # # 创建对象
        # serializer = TJSS(secret_key=settings.SECRET_KEY, expires_in=60 * 15)
        #
        # # 生成access_token
        # # dumps( Like :meth:`.Serializer.dumps` but creates a JSON WebSignature.)
        # token = serializer.dumps(mobile).decode()

        # 4. 返回响应
        context = {
            "errmsg": '发送成功',
            "code": RET.OK,
        }
        return http.JsonResponse(context)

class AccountsPwdView(View):
    def get(self,request,username):
        # 1,获取参数
        sms_code = request.GET.get("sms_code")
        try:
            # 1,先判断username是否是手机号
            if re.match(r'^1[3-9]\d{9}$', username):

                user = User.objects.get(mobile=username)
            else:
                # 2,然后在通过用户名查询,用户
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return http.JsonResponse({"errmsg": "账号不存在", "status": RET.NODATA})
        mobile = user.mobile

        # 2,校验参数
        if not all([sms_code,username,mobile]):
            return http.HttpResponseForbidden("参数不全")

        # 3 短信验证码校验
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_code_%s' % mobile).decode()
        if not redis_sms_code:
            return http.HttpResponseForbidden('验证码已过期')
        # print(redis_sms_code)
        if sms_code != redis_sms_code:
            return http.HttpResponseForbidden('验证码错误')

        # 4 生成access_token
        # 创建对象
        serializer = TJSS(secret_key=settings.SECRET_KEY, expires_in=60 * 15)

        # 生成token
        # dumps( Like :meth:`.Serializer.dumps` but creates a JSON WebSignature.)
        token = serializer.dumps(mobile).decode()

        # 5 拼接数据
        context = {
            "user_id":user.id,
            "access_token":token,
            "code": RET.OK,
        }
        return http.JsonResponse(context)

class PasswordReset(View):
    def post(self,request,user_id):
        dict_data = json.loads(request.body.decode())

        password = dict_data.get("password")
        password2 = dict_data.get("password2")
        access_token = dict_data.get("access_token")

        print(access_token)
        if not all([password,password2]):
            return http.HttpResponseForbidden("参数不全")

        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseForbidden("密码格式有误")

        if password != password2:
            return http.HttpResponseForbidden('两次密码不一致')

        user = User.objects.get(id=user_id)
        if not user:
            return http.HttpResponseForbidden("账号或手机号不存在")

        # 创建对象
        serializer = TJSS(secret_key=settings.SECRET_KEY, expires_in=60 * 15)
        # 解密
        try:
            mobile = serializer.loads(access_token)
            user = User.objects.get(mobile=mobile)
        except:
            return None
        if not user:
            return http.HttpResponseForbidden('无效的token')

        if user.mobile != mobile:
            return http.HttpResponseForbidden("修改密码失败")

        # 数据入库
        user.set_password(password)
        user.save()

        context= {
            "status":RET.OK,
        }
        return http.JsonResponse(context)
